﻿using System.Collections.Concurrent;
using Microsoft.AspNetCore.SignalR;

namespace SignalR.Server.Hubs
{
    public class ChatHub : Hub
    {
        public static readonly ConcurrentDictionary<string, bool> ConnectedConnections = new ConcurrentDictionary<string, bool>();

        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, "服务端收到了客户端的消息：" + message);
        }
        public override async Task OnConnectedAsync()
        {
            await Clients.All.SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} joined the chat");
            ConnectedConnections.TryAdd(Context.ConnectionId, true);
            await base.OnConnectedAsync();
        }
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await Clients.All.SendAsync("ReceiveMessage", "System", $"{Context.ConnectionId} left the chat");
            ConnectedConnections.TryRemove(Context.ConnectionId, out _);
            await base.OnDisconnectedAsync(exception);
        }
    }
}
